package com.behelpful.common.core.utils;

import com.behelpful.common.core.exceptions.IRuntimeException;
import com.behelpful.common.core.result.BaseResult;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

import java.lang.reflect.Constructor;

/**
 * 异常工具类
 *
 * @author Alay
 * @date 2021-08-17 09:43
 * @since
 */
@UtilityClass
public class ExceptionUtil {

    /**
     * 创建一个异常对象实例,此函数没有做过多的逻辑处理,要求必须具备空餐构造器且public修饰
     *
     * @param eClazz
     * @param <E>
     * @return
     */
    @SneakyThrows
    public <E extends IRuntimeException> E create(Class<E> eClazz) {
        Constructor<E> constructor = eClazz.getConstructor();
        E exceptionInstance = constructor.newInstance();
        return exceptionInstance;
    }

    /**
     * 创建一个异常对象实例,要求必须具备空餐构造器
     *
     * @param eClazz
     * @param baseResult
     * @param <E>
     * @return
     */
    @SneakyThrows
    public <E extends IRuntimeException> E create(Class<E> eClazz, BaseResult baseResult) {
        Constructor<E> constructor = eClazz.getConstructor();
        E exceptionInstance = constructor.newInstance(baseResult);
        return exceptionInstance;
    }

    /**
     * 抛出异常
     *
     * @param eClazz
     * @param <E>
     */
    public <E extends IRuntimeException> void doThrow(Class<E> eClazz) {
        throw create(eClazz);
    }

    /**
     * 抛出异常
     *
     * @param eClazz
     * @param <E>
     */
    public <E extends IRuntimeException> void doThrow(Class<E> eClazz, BaseResult baseResult) {
        throw create(eClazz, baseResult);
    }

}
